import torch
import torch.nn as nn

class AlexNet(nn.Module):
    def __init__(self, num_classes=1000):
        super(AlexNet, self).__init__()
        self.model_name = "AlexNet"

        self.con1 = nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2)
        self.relu1 = nn.ReLU(inplace=True)
        self.max1 = nn.MaxPool2d(kernel_size=3, stride=2)
        self.con2 = nn.Conv2d(64, 192, kernel_size=5, stride=1, padding=2)
        self.relu2 = nn.ReLU(inplace=True)
        self.max2 = nn.MaxPool2d(kernel_size=3, stride=2)
        self.con3 = nn.Conv2d(192, 384, kernel_size=3, stride=1, padding=1)
        self.relu3 = nn.ReLU(inplace=True)
        self.con4 = nn.Conv2d(384, 256, kernel_size=3, stride=1, padding=1)
        self.relu4 = nn.ReLU(inplace=True)
        self.con5 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
        self.relu5 = nn.ReLU(inplace=True)
        self.max3 = nn.MaxPool2d(kernel_size=3, stride=2)

        self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
        self.classifier = nn.Sequential(
            nn.Dropout(),
            nn.Linear(6 * 6 * 256, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes)
        )

    def features(self,x):
        x = self.relu1(self.con1(x)) #[batchsize, 64,54,54]
        x = self.max1(x) #[batchsize, 64,26,26]
        x = self.relu2(self.con2(x)) #[batchsize, 192,26,26]
        x = self.max2(x) #[batchsize, 192,12,12]
        x = self.relu3(self.con3(x)) #[batchsize, 384,12,12]
        x = self.relu4(self.con4(x)) #[batchsize, 256,12,12]
        x = self.relu5(self.con5(x)) #[batchsize, 256,12,12]
        x = self.max3(x) #[batchsize, 256,5,5]
        return x

    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        x = x.reshape(x.size(0), -1)
        out = self.classifier(x)
        return out

class VGG(nn.Module):

    def __init__(
        self,
        features: nn.Module,
        num_classes: int = 1000,
        init_weights: bool = True
    ) -> None:
        super(VGG, self).__init__()
        self.model_name = "VGG"
        self.features = features
        self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, num_classes),
        )
        if init_weights:
            self._initialize_weights()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.features(x)
        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x

    def _initialize_weights(self) -> None:
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)

def make_layers(cfg, batch_norm=False):
    '''
    根据配置表，返回模型层列表
    '''
    layers = [] # 层列表初始化

    in_channels = 3 # 输入3通道图像

    # 遍历配置列表
    for v in cfg:
        if v == 'M': # 添加池化层
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else: # 添加卷积层

            # 3×3 卷积
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)

            # 卷积-->批归一化（可选）--> ReLU激活
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
            else:
                layers += [conv2d, nn.ReLU(inplace=True)]

            # 通道数方面，下一层输入即为本层输出
            in_channels = v

    # 以sequencial类型返回模型层列表
    return nn.Sequential(*layers)


# 网络参数配置表
'''
数字代表通道数，如 64 表示输出 64 通道特征图，对应于论文中的 Conv3-64;
M 代表最大池化操作，对应于论文中的 maxpool 
A-LRN使用了局部归一化响应，C网络存在1×1卷积，这两个网络比较特殊，所以排除在配置表中
'''
cfgs = {
    'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}

